<template>
  <div class="fty-box">
    <div class="box-header">
      <h1>
        <i class="el-icon-user title-logo" />
        {{ $t('common.users') }}
      </h1>
    </div>
    <hr class="mb-2">
    <el-card
      shadow="never"
      class="fty-card"
      :body-style="{padding: '0px'}"
      @current-change="currentChangeHandle"
      :page-size="pageSize"
      :total="totalPage"
      :current-page="pageIndex"
    >
      <div class="search-box">
        <el-form @submit.prevent.native inline>
          <el-form-item>
            <el-input
              maxlength="64"
              v-model="condition"
              @blur="() => condition = condition.trim()"
              @keyup.enter.native="fetchData(pageIndex = 1)"
              :placeholder="$t('system.user.query_condition')"
              size="small"
              style="width: 290px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="p-1.5 align-middle" size="small" @click="fetchData(pageIndex = 1)">
              <svg-icon icon-class="search" class="text-lg" />
            </el-button>
            <el-button
              v-permission="{
                permission: '12408000.MANAGE'
              }"
              type="primary"
              @click="handleAdd()"
              size="small"
              class="p-1.5 align-middle"
            >
              <svg-icon icon-class="add_btn" class="text-lg" />
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :show-overflow-tooltip="true" v-loading="listLoading" :data="tableData">
        <el-table-column prop="username" align="left" width="70px">
          <template slot-scope="{ row }">
            <div
              class="user-list-avatar"
            >
              <img
                :src="getLogo(row.logoUrl)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('system.user.user_name')" prop="username" align="left" />
        <el-table-column :label="$t('system.user.name')" prop="name" align="center" />
        <el-table-column :label="$t('system.user.organization')" prop="orgName" align="center" />
        <el-table-column label="TOMS" prop="haveTOMS" align="center">
          <template slot-scope="{ row }">
            <el-tag
              size="small"
              :type="row.haveTOMS == '0' ? 'danger' : 'success'"
            >
              <span>{{ tomsFilter(row.haveTOMS ) }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.status')" prop="status" align="center">
          <template slot-scope="{ row }">
            <el-tag
              size="small"
              :type="row.status == 0 ? 'danger' : (row.status == 1 ? 'success' : '')"
            >
              <span>{{ statusFilter(row.status ) }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.create_time')" prop="creTime" align="center">
          <template slot-scope="{ row }">
            <div :title="row.creTime | timeFilter">{{ row.creTime | dateFilter }}</div>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('system.user.last_login_time')"
          prop="lastLoginTime"
          align="center"
        >
          <template slot-scope="{ row }">
            <div :title="row.lastLoginTime | timeFilter">{{ row.lastLoginTime | dateFilter }}</div>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" width="50">
          <template slot-scope="scope">
            <el-dropdown
              v-if="verifyPermission('12408000.MANAGE') && scope.row.username != loginUserName && scope.row.managerFlag != 1"
              @command="handleClick"
            >
              <span class="el-dropdown-link">
                <svg-icon icon-class="menu" style="font-size: 20px;" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="beforeHandleCommand('edit', scope.row)">
                  <i class="el-icon-edit" style="margin-top: 10px; margin-right: 15px"></i>
                  <span>{{ $t('common.edit') }}</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="scope.row.status === 1"
                  :command="beforeHandleCommand('lock', scope.row)"
                >
                  <i class="el-icon-lock" style="margin-top: 10px; margin-right: 15px"></i>
                  <span>{{ $t('common.lock') }}</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="scope.row.status === 0"
                  :command="beforeHandleCommand('unlock', scope.row)"
                >
                  <i class="el-icon-unlock" style="margin-top: 10px; margin-right: 15px"></i>
                  <span>{{ $t('common.unlock') }}</span>
                </el-dropdown-item>
                <el-dropdown-item :command="beforeHandleCommand('resetPassword', scope.row)">
                  <i class="el-icon-refresh" style="margin-top: 10px; margin-right: 15px"></i>
                  <span>{{ $t('system.user.reset_password') }}</span>
                </el-dropdown-item>
                <el-dropdown-item :command="beforeHandleCommand('delete', scope.row)">
                  <i class="el-icon-delete" style="margin-top: 10px; margin-right: 15px"></i>
                  <span>{{ $t('common.delete') }}</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <user-add
      ref="userDialog"
      :type="operationType"
      :user-id="editUserId"
      @submit="fetchData"
      @addRole="addRole"
      :visible.sync="addUserVisible"
      :title="editUserId ? $t('system.user.edit_user') : $t('system.user.add_user')"
    ></user-add>

    <role-add
      type="add"
      :role-id="editRoleId"
      :visible.sync="addRoleVisible"
      :title="$t('system.role.add_role')"
      @submit="openUserDialog"
    />
  </div>
</template>

<script>
import { getUserPage, lockUser, unlockUser, resetPassword, deleteUser } from '@/api/user'
import { timeFilter, dateFilter } from '@/filters'
import UserAdd from './user-add'
import { verifyBtnPermission } from '@/utils'
import RoleAdd from '../role/role-add'

export default {
  filters: {
    timeFilter,
    dateFilter
  },
  components: {
    UserAdd,
    RoleAdd
  },
  data() {
    return {
      loginUserName: '',
      tableData: [],
      listLoading: false,
      selectedData: [],
      paginationShow: true,
      condition: '',
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      operationType: '',
      editUserId: '',
      addUserVisible: false,
      editRoleId: '',
      addRoleVisible: false
    }
  },
  mounted() {
    const userInfo = JSON.parse(localStorage.getItem(this.$store.getters.keys.storage.username))
    this.loginUserName = userInfo.username
    this.fetchData()
  },
  methods: {
    statusFilter(status) {
      const statusMap = {
        0: this.$t('common.locked'),
        1: this.$t('common.valid')
      }
      return statusMap[status]
    },
    tomsFilter(status) {
      const statusMap = {
        '1': this.$t('common.flycare_open'),
        '0': this.$t('common.flycare_close')
      }
      return statusMap[status]
    },
    addRole() {
      console.log('addRole')
      this.addRoleVisible = true
    },
    openUserDialog() {
      console.log('openUserDialog')
      this.addUserVisible = true
    },
    verifyPermission(val){
      return verifyBtnPermission(val)
    },
    fetchData() {
      this.listLoading = true
      getUserPage({
        pageNo: this.pageIndex,
        pageSize: this.pageSize,
        status: '',
        condition: this.condition
      }).then((res) => {
        this.listLoading = false
        this.tableData = res.data
        this.totalPage = res.rows
        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].platCode !== null) {
            this.tableData[i]['haveTOMS'] = '0'
            for (let j = 0; j < this.tableData[i].platCode.length; j++) {
              if (this.tableData[i].platCode[j].toUpperCase() === 'TOMS') {
                this.tableData[i]['haveTOMS'] = '1'
              }
            }
          } else {
            this.tableData[i]['haveTOMS'] = '0'
          }
        }
      }).catch((e) => {
        this.listLoading = false
        this.$confirmError(e)
      })
    },
    handleDetails(row, column, e) {
      this.$router.push({
        path: `/estate/batch/details/${row.batchNo}`
      })
    },
    getLogo(logo){
      if(logo){
        let avatars = this.$store.getters.avatars.find(v => v.name == logo)
        if(avatars){
          return avatars.src
        }
      }
      return this.$store.getters.avatars[0].src
    },
    handleLock(row) {
      this.$confirm(
        this.$t('modules.permission.user.sure_to_lock_user') +
          `[${row.email}]?`,
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      ).then(() => {
        lockUser(row.userId).then((res) => {
          this.$message({
            message: this.$t('modules.permission.user.lock_success'),
            type: 'success',
          })
          this.fetchData()
        }).catch(this.$confirmError)
      })
    },
    handleUnlock(row) {
      this.$confirm(
        this.$t('modules.permission.user.sure_to_unlock_user') +
          `[${row.email}]?`,
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      ).then(() => {
        unlockUser(row.userId).then((res) => {
          this.$message({
            message: this.$t('modules.permission.user.unlock_success'),
            type: 'success',
          })
          this.fetchData()
        }).catch(this.$confirmError)
      })
    },
    handleClick(val) {
      let command = val.command
      let row = val.row
      if (command === 'edit') {
        this.handleEdit(row)
      } else if (command === 'lock') {
        this.handleLock(row)
      } else if (command === 'unlock') {
        this.handleUnlock(row)
      } else if (command === 'resetPassword') {
        this.handleResetPassword(row)
      } else if (command === 'delete') {
        this.handleDelete(row)
      }
    },
    beforeHandleCommand(command, row) {
      return {
        row: row,
        command: command
      }
    },
    handleResetPassword(row) {
      this.$confirm(
        this.$t('modules.permission.user.sure_to_reset_password'),
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      ).then(() => {
        resetPassword(row.userId).then((res) => {
          this.$message({
            message: this.$t('modules.permission.user.reset_password_success'),
            type: 'success',
          })
          this.fetchData()
        }).catch(this.$confirmError)
      })
    },
    handleDelete(row) {
      this.$confirm(
        this.$t('modules.permission.user.sure_to_delete_user') +
          `[${row.email}]?`,
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      ).then(() => {
        deleteUser(row.userId).then((res) => {
          this.$message({
            message: this.$t('modules.permission.user.delete_success'),
            type: 'success',
          })
          this.fetchData()
        }).catch(this.$confirmError)
      })
    },
    handleEdit(row) {
      this.operationType = 'Update'
      this.editUserId = row.userId
      this.addUserVisible = true
      // this.$refs.userDialog.clear()
      this.$refs.userDialog.init(row.userId)
    },
    handleAdd() {
      this.operationType = 'Add'
      this.editUserId = ''
      this.addUserVisible = true
      this.$refs.userDialog.clear()
      this.$refs.userDialog.init('')
    },
    sizeChangeHandle(val) {
      this.pageSize = val
      this.fetchData()
    },
    currentChangeHandle(val) {
      this.pageIndex = val
      this.fetchData()
    }
  }
}
</script>

<style lang="scss">
.terminal-list {
  .el-table .cell {
    /* height: 30px !important; */
  }
}
</style>

<style lang="scss" scoped>
.query-button {
  margin-left: 30px;
}
.svg-container {
  cursor: pointer;
  margin-top: 6px;
  margin-left: 20px;
  font-size: 24px;
  display: inline-block;
}
.user-list-avatar {
  width: 43.8px;
  height: 43.8px;
  border-radius: 60px;
  overflow: hidden;
  margin: 5px;
  img {
    margin-right: 5px;
    border-radius: 50%;
  }
}
.pagination-wrapper {
  text-align: right;
}
</style>
